import {confirmCconfig,socketNowIP} from "@/utils/config"
import router from '@/router'
import {
	Message,
	MessageBox
} from 'element-ui'
import socket from "@/socket";
import {
	getToken,
	removeToken
} from '@/utils/auth'
import sessionStorage from '@/utils/session'

const socketService = {
	socket: null,
	newMessage: null,
	fromId: 0,
	username: "",
	url: "",
	nowIP: socketNowIP,
	isGetRelationshiplist: false, //是否重新请求联系人
	userlist: [], //联系人ID表
	confirmed:true,//是否弹窗 一次只能弹一个
	HeartBeatItem:0,//心跳检测标识
	init(userID, userName) {
		if (typeof WebSocket === "undefined") {
			alert("您的浏览器不支持socket");
		} else {
			let path = socketNowIP+ userID + "/" + userName + "/" + getToken(); // 请求路径
			this.socket = new WebSocket(path);
			this.socket.onopen = this.open.bind(this);
			this.socket.onerror = this.error.bind(this);
			this.socket.onmessage = this.getMessage.bind(this);
			this.socket.onclose = this.close.bind(this);
			clearInterval(this.HeartBeatItem)
			this.HeartBeatItem=setInterval(()=>{
				this.socket.send(JSON.stringify({type:10,data:"30sHeartBeat"}));
			},30000)
		}
	},
	open() {
		console.log("socket连接成功");
	},
	error() {
		console.log("连接错误");
	},
	//接受信息
	getMessage() {
		return new Promise((resolve, reject) => {
			this.socket.onmessage = (event) => {
				// 利用promise 返回出去结果
				if (typeof event.data === 'string') {
					var message = JSON.parse(event.data);
					if (confirmCconfig.isTure && message.type===-1 && message.code===401) {
						confirmCconfig.isTure = false;
						// removeToken();
						sessionStorage.removeSession();
						MessageBox.confirm('登录失效，可以取消继续留在该页面,或者重新登录', '提示', {
							confirmButtonText: '重新登录',
							cancelButtonText: '取消',
							type: 'warning'
						}).then((data) => {
							confirmCconfig.isTure = true;
							router.push('/login')
							reject("token失效");
							this.socket.onclose();//关闭连接
						}).catch(err=>{
							confirmCconfig.isTure = true;
							this.socket.onclose();//关闭连接
							reject("token失效");
						})
						return;
					}
					this.newMessage = Object.assign({}, message);
					this.conversation = message.content;
					this.userCount = message.userCount;
					resolve(message);
				}
			};
		});

	},
	//发送信息
	send(data) {
		this.socket.send(JSON.stringify(data));
	},
	close() {
		sessionStorage.removeSession();
		removeToken();
		console.log("socket已经关闭");
	}
};
//最后导出
export default socketService;